package com.zhuzi.utils;

import cn.hutool.core.thread.ThreadUtil;
import com.alibaba.fastjson2.JSON;
import com.google.common.collect.Lists;
import com.zhuzi.common.utils.LocalDateTimeUtils;
import com.zhuzi.dto.jc.JcEntityDTO;
import com.zhuzi.dto.jc.SearchResultDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.jsoup.Connection;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 巨潮新闻抓取utils
 */
@Slf4j
public class JcNewsGetUtils {
    /**
     * Java 8 Function 函数接口
     */
    public static Function<SearchResultDTO.Announcements, JcEntityDTO> searchToDTO = item -> {
        LocalDateTime convert = LocalDateTimeUtils.convert(item.getAnnouncementTime());
        JcEntityDTO jcEntity = new JcEntityDTO();
        jcEntity.setSecCode(item.getSecCode());
        jcEntity.setSecName(item.getSecName());
        jcEntity.setAnnId(item.getAnnouncementId());
        jcEntity.setAnnTitle(item.getAnnouncementTitle());
        jcEntity.setAdjunctUrl(item.getAdjunctUrl());
        jcEntity.setAdjunctType(item.getAdjunctType());
        jcEntity.setPubDate(convert.toLocalDate());
        jcEntity.setPubDateTime(convert);
        jcEntity.setFetchDate(LocalDateTime.now());
        return jcEntity;
    };

    public static void main(String[] args) {

        List<JcEntityDTO> list = fetch("减持", LocalDate.now().minusDays(1), LocalDate.now().plus(1, ChronoUnit.DAYS));
        System.out.println(list.size());
    }

    /**
     * 获取巨潮公告
     *
     * @param keys 检索关键字
     * @return {@link List}<{@link JcEntityDTO}>
     */
    public static List<JcEntityDTO> fetch(String keys, LocalDate startDate, LocalDate endDate) {
        List<JcEntityDTO> result = Lists.newCopyOnWriteArrayList();
        ConcurrentSkipListMap<String, String> map = new ConcurrentSkipListMap<>();
        map.putIfAbsent("pageSize", "30");
        map.putIfAbsent("column", "szse");
        map.putIfAbsent("tabName", "fulltext");
        map.putIfAbsent("plate", "");
        //"减持公司可转换"
        map.putIfAbsent("searchkey", keys);
        map.putIfAbsent("stock", "");
        // "2021-08-23~2022-02-23"
        map.putIfAbsent("seDate", String.format("%s~%s", startDate, endDate));
        map.putIfAbsent("sortName", "");
        map.putIfAbsent("sortType", "");
        map.putIfAbsent("isHLtitle", "false");
        map.putIfAbsent("secid", "");
        map.putIfAbsent("category", "");
        map.putIfAbsent("trade", "");
        String url = "http://www.cninfo.com.cn/new/hisAnnouncement/query";
        for (int i = 1; ; i++) {
            map.put("pageNum", i + "");
            try {
                Connection.Response response = JsoupHttpUtils.post(url, Collections.EMPTY_MAP, map, Collections.EMPTY_MAP, Collections.EMPTY_MAP);
                SearchResultDTO searchResultDTO = JSON.parseObject(response.body(), SearchResultDTO.class);
                if (CollectionUtils.isNotEmpty(searchResultDTO.getAnnouncements())) {
                    List<JcEntityDTO> collect = searchResultDTO.getAnnouncements().stream().map(searchToDTO).collect(Collectors.toList());
                    result.addAll(collect);
                }
                if (!searchResultDTO.isHasMore()) {
                    break;
                }
                ThreadUtil.sleep(500 * 3, TimeUnit.MILLISECONDS);
                log.info("巨潮公告-第[{}]页-[{}]", i, keys);
            } catch (IOException e) {
                return result;
            }
        }
        return result;
    }
}
